package org.apogee.mil.server.trainer;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.apogee.mil.client.services.trainer.TrainerService;
import org.apogee.mil.server.database.DatabaseDriver;
import org.apogee.mil.server.database.helper.DatabaseQueries;
import org.apogee.mil.shared.Constants.DisplayFormat;
import org.apogee.mil.shared.Constants.TrainerTraineeLookupFields;
import org.apogee.mil.shared.Constants.UserLookupFields;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TrainerServiceImpl extends RemoteServiceServlet implements TrainerService {

	private static Logger logger = Logger.getLogger(TrainerServiceImpl.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private DatabaseDriver db;

	@Override
	public boolean initialize() {
		db = new DatabaseDriver();
		return db.initialize();
	}

	@Override
	public boolean close() {
		try {
			return db.close();
		} catch (NullPointerException ex) {
			return false;
		}
	}
	@Override
	public ArrayList<BaseModel> getTrainees(int trainerId) {

		String stmt = String.format(DatabaseQueries.GET_USERS_BY_TRAINER_ID, 
				UserLookupFields.USER_ID, UserLookupFields.FIRST_NAME, UserLookupFields.LAST_NAME,
				TrainerTraineeLookupFields.TRAINEE_ID, UserLookupFields.USER_ID, TrainerTraineeLookupFields.TRAINER_ID, trainerId);


		ArrayList<BaseModel> trainees = new ArrayList<BaseModel>();

		ResultSet set = db.executeQuery(stmt);

		try {
			while (set.next()) {
				BaseModel bm = new BaseModel();

				String userId = set.getString(UserLookupFields.USER_ID);
				String fName = set.getString(UserLookupFields.FIRST_NAME);
				String lName = set.getString(UserLookupFields.LAST_NAME);

				bm.set(DisplayFormat.USER_FMT, userId + " - " + fName + " " + lName);
				trainees.add(bm);
			}
		} catch (SQLException e) {
			logger.error(e);
		}

		return trainees;
	}
	
	
}
